﻿// ServiceManager.cs
using Honest.MES.Contracts.Interfaces;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Honest.MES.Contracts.Services
{
    public class ServiceManager
    {
        private readonly List<IServiceBase> _services = new List<IServiceBase>();
        private readonly IEventAggregator _eventAggregator;

        public IReadOnlyCollection<IServiceBase> Services => _services.AsReadOnly();

        public ServiceManager(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
        }

        public void RegisterService(IServiceBase service)
        {
            _services.Add(service);
            // 可选：发布服务注册事件
            // _eventAggregator.GetEvent<ServiceRegisteredEvent>().Publish(service);
        }

        public async Task StartAllAsync()
        {
            var servicesToStart = _services
                .Where(s => s.AutoStart)
                .OrderBy(s => s.Level)
                .ThenBy(s => s.DelayTime)
                .ToList();

            foreach (var service in servicesToStart)
            {
                try
                {
                    if (service.DelayTime > 0)
                        await Task.Delay(service.DelayTime);

                    await service.InitService();
                    await service.OnService();

                    // 发布服务启动事件（可用于 UI 更新）
                    _eventAggregator.GetEvent<ServiceStatusChangedEvent>()
                        .Publish(new ServiceStatusInfo(service.Name, "Running", service.GetStatusInfo()));
                }
                catch (Exception ex)
                {
                    // 您可以集成日志服务
                    Console.WriteLine($"服务启动失败: {service.Name} | {ex.Message}");
                }
            }
        }

        public async Task StopAllAsync()
        {
            var reversed = _services.OrderByDescending(s => s.Level).ToList();
            foreach (var service in reversed)
            {
                if (service.IsActive)
                {
                    await service.OffService();
                    _eventAggregator.GetEvent<ServiceStatusChangedEvent>()
                        .Publish(new ServiceStatusInfo(service.Name, "Stopped"));
                }
            }
        }

        public async Task ExitAllAsync()
        {
            foreach (var service in _services)
            {
                await service.ExitService();
            }
        }
    }

    // 用于 UI 通知的事件数据
    public class ServiceStatusInfo
    {
        public string ServiceName { get; }
        public string Status { get; }
        public string Detail { get; }
        public ServiceStatusInfo(string name, string status, string detail = null)
        {
            ServiceName = name;
            Status = status;
            Detail = detail;
        }
    }

    // Prism 事件定义
    public class ServiceStatusChangedEvent : PubSubEvent<ServiceStatusInfo> { }
    public class ServiceRegisteredEvent : PubSubEvent<IServiceBase> { }
}